<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,Concurrent," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="在我们讨论CAS锁之前先来看一个简单的java操作；在单线程环境中执行时i的值为1，然而在多线程环境中i的值却不一定。int i=0;i++; i++这个操作的具体步骤其实有三部：  从内存中获取i原来的值 对i的值执行加1操作 将i增加后的值重新写入到内存cpu在执行这三个步骤时，都不能保证原子性，任何一步都有可能被其他线程抢占cpu而挂起。  为了实现操作的原子性，一种很常见的方式就是加锁。i">
<meta name="keywords" content="java,Concurrent">
<meta property="og:type" content="article">
<meta property="og:title" content="CAS锁机制，AtomicInteger实现">
<meta property="og:url" content="https://gitee.com/shuhao/2018/01/25/CAS锁机制，AtomicInteger实现/index.html">
<meta property="og:site_name" content="Niki">
<meta property="og:description" content="在我们讨论CAS锁之前先来看一个简单的java操作；在单线程环境中执行时i的值为1，然而在多线程环境中i的值却不一定。int i=0;i++; i++这个操作的具体步骤其实有三部：  从内存中获取i原来的值 对i的值执行加1操作 将i增加后的值重新写入到内存cpu在执行这三个步骤时，都不能保证原子性，任何一步都有可能被其他线程抢占cpu而挂起。  为了实现操作的原子性，一种很常见的方式就是加锁。i">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-07-19T07:46:18.264Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="CAS锁机制，AtomicInteger实现">
<meta name="twitter:description" content="在我们讨论CAS锁之前先来看一个简单的java操作；在单线程环境中执行时i的值为1，然而在多线程环境中i的值却不一定。int i=0;i++; i++这个操作的具体步骤其实有三部：  从内存中获取i原来的值 对i的值执行加1操作 将i增加后的值重新写入到内存cpu在执行这三个步骤时，都不能保证原子性，任何一步都有可能被其他线程抢占cpu而挂起。  为了实现操作的原子性，一种很常见的方式就是加锁。i">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/shuhao/2018/01/25/CAS锁机制，AtomicInteger实现/"/>





  <title> CAS锁机制，AtomicInteger实现 | Niki </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb9f0585e406f878cb2f29c89ad3cdb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Niki</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天道酬勤</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-categories"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/shuhao/blog/2018/01/25/CAS锁机制，AtomicInteger实现/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Fang ShuHao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Niki">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                CAS锁机制，AtomicInteger实现
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-25T19:20:37+08:00">
                2018-01-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在我们讨论CAS锁之前先来看一个简单的java操作；在单线程环境中执行时i的值为1，然而在多线程环境中i的值却不一定。<br><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">int</span> i=<span class="number">0</span>;</span><br><span class="line">i++;</span><br></pre></td></tr></table></figure></p>
<p>i++这个操作的具体步骤其实有三部：</p>
<ol>
<li>从内存中获取i原来的值</li>
<li>对i的值执行加1操作</li>
<li>将i增加后的值重新写入到内存<br>cpu在执行这三个步骤时，都不能保证原子性，任何一步都有可能被其他线程抢占cpu而挂起。</li>
</ol>
<p>为了实现操作的原子性，一种很常见的方式就是加锁。<br><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">int</span> i=<span class="number">0</span>;</span><br><span class="line">synchronize&#123;</span><br><span class="line">	i++;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>原子性的问题解决了，（关灯睡觉~~），等等，听大牛们说过，在高并发的场景，synchronize的性能不好。<br>是的，在高并发的场景中，如果线程频繁的挂起阻塞，将会增加系统切换线程的消耗，以及重新竞争cpu时间片的资源消耗。那么如何在保证原子性的同时，确保高并发的性能呢？<br>对了，CAS为我们提供了一个解决方案。</p>
<h2 id="CAS（compare-and-swap）"><a href="#CAS（compare-and-swap）" class="headerlink" title="CAS（compare and swap）"></a>CAS（compare and swap）</h2><p>使用CAS机制实现的锁其实是一种乐观锁的方式。<br>乐观锁假设不会发生冲突，一直重试。知道完成修改。<br>所以，在修改共享变量的时候，发现变量冲突，线程并不会挂起，而是一直重试，直到冲突解决然后完成变量的修改。</p>
<h2 id="CAS实现"><a href="#CAS实现" class="headerlink" title="CAS实现"></a>CAS实现</h2><ol>
<li><p>CAS的实现首先需要硬件的支持。需要处理器支持实现名为<strong><em>比较转换</em></strong>或<strong><em>CAS</em></strong>的原语。（在 Intel 处理器中，比较并交换通过指令的 cmpxchg 系列实现。PowerPC 处理器有一对名为“加载并保留”和“条件存储”的指令，它们实现相同的目地；MIPS 与 PowerPC 处理器相似，除了第一个指令称为“加载链接”。）</p>
</li>
<li><p>CAS操作包含三个操作数<br><strong><em>内存位置（V）</em></strong>、<strong><em>预期原值（A）</em></strong>、<strong><em>新值（B）</em></strong><br>处理器会从内存位置V处读取值oldA，并且将oldA的值与预期原值A进行比较，如果一样，则认为该值没有被同步修改，将oldA的值修改为新增B。如果读取的值与预期原值不一致，则失败。</p>
</li>
</ol>
<h2 id="AtomicInteger实现"><a href="#AtomicInteger实现" class="headerlink" title="AtomicInteger实现"></a>AtomicInteger实现</h2><p>在多线程下 i++ （int i =0）这个操作是线程不安全的，那么AtomicInteger是怎么保证线程安全的自增？看下源码：<br><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Atomically increments by one the current value.</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> the updated value</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">int</span> <span class="title">incrementAndGet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> unsafe.getAndAddInt(<span class="keyword">this</span>, valueOffset, <span class="number">1</span>) + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// unsafe是java提供的获得对对象内存地址访问的类</span></span><br><span class="line"><span class="comment">//unsafe中getAndAddInt方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">int</span> <span class="title">getAndAddInt</span><span class="params">(Object var1, <span class="keyword">long</span> var2, <span class="keyword">int</span> var4)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> var5;</span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">        	<span class="comment">//获取存储位置上的原值</span></span><br><span class="line">            var5 = <span class="keyword">this</span>.getIntVolatile(var1, var2);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//判断获取的原值在自增时（var4 = 1）是否和内存中一样，如果不一样则再次获取内存中的值，再次进行加var4操作，直到成功。</span></span><br><span class="line">        &#125; <span class="keyword">while</span>(!<span class="keyword">this</span>.compareAndSwapInt(var1, var2, var5, var5 + var4));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> var5;<span class="comment">//返回自加之前的值</span></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>从源码中可以看出，AtomicInteger也是实现了CAS的原理。来实现并发情况下的安全自增。</p>
<h2 id="乐观锁，悲观锁"><a href="#乐观锁，悲观锁" class="headerlink" title="乐观锁，悲观锁"></a>乐观锁，悲观锁</h2><ul>
<li><p>悲观锁：当执行的条件不允许时，让出cpu进入阻塞队列直到条件允许时，唤醒进入runnable状态等待执行。这是典型的独占锁。synchronized就是独占锁，是一种悲观锁。</p>
</li>
<li><p>乐观锁：每次不加锁假设没有冲突而去完成某项操作，如果因为冲突失败就去重试，直到成功为止。当数据争用不严重时，乐观锁效果更好。CAs就是一种悲观锁。</p>
</li>
</ul>
<h2 id="CAS缺点"><a href="#CAS缺点" class="headerlink" title="CAS缺点"></a>CAS缺点</h2><p>CAS从某种意义上保证了操作的原子性，但是只是一种弱实现；还是可能会出现ABA问题。</p>
<h3 id="ABA问题"><a href="#ABA问题" class="headerlink" title="ABA问题"></a>ABA问题</h3><p>ABA问题(即在更新前的值是A，但在操作过程中被其他线程更新为B，又更新为 A)，这时当前线程认为是可以执行的，其实是发生了不一致现象，如果这种不一致对程序有影响(真正有这种影响的场景很少，除非是在变量操作过程中以此变量为标识位做一些其他的事，比如初始化配置)，则需要使用AtomicStampedReference(除了对更新前的原值进行比较，也需要用更新前的 stamp标志位来进行比较)。</p>
<p><strong><em>CAS实现了无锁的情况下实现原子性，在高并发的情况下实现非阻塞操作。但是在复杂操作中（数据争用比较频繁）的场景中不推荐使用CAS。</em></strong></p>
<blockquote>
<blockquote>
<p>参考<br><a href="http://mp.weixin.qq.com/s/--AMdl0GZQkY1MWIWQ-HHA" target="_blank" rel="external">深入分析CAS</a></p>
</blockquote>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/java/" rel="tag"># java</a>
          
            <a href="/blog/tags/Concurrent/" rel="tag"># Concurrent</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/01/25/ConcurrentLinkedQueue-ArrayBlockingQueue-LinkedBlockingQueue/" rel="next" title="ConcurrentLinkedQueue, ArrayBlockingQueue, LinkedBlockingQueue">
                <i class="fa fa-chevron-left"></i> ConcurrentLinkedQueue, ArrayBlockingQueue, LinkedBlockingQueue
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/01/25/分段锁机制与ConcurrentHashMap/" rel="prev" title="分段锁机制与ConcurrentHashMap">
                分段锁机制与ConcurrentHashMap <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNjY5NS8xMzIzMA=="></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/head.jpg"
               alt="Fang ShuHao" />
          <p class="site-author-name" itemprop="name">Fang ShuHao</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">135</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">93</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#CAS（compare-and-swap）"><span class="nav-number">1.</span> <span class="nav-text">CAS（compare and swap）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CAS实现"><span class="nav-number">2.</span> <span class="nav-text">CAS实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#AtomicInteger实现"><span class="nav-number">3.</span> <span class="nav-text">AtomicInteger实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#乐观锁，悲观锁"><span class="nav-number">4.</span> <span class="nav-text">乐观锁，悲观锁</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CAS缺点"><span class="nav-number">5.</span> <span class="nav-text">CAS缺点</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ABA问题"><span class="nav-number">5.1.</span> <span class="nav-text">ABA问题</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fang ShuHao</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  



  
  

  

  

  

  


  

</body>
</html>
